package models

type SystemSubject struct {
	Id          int       `json:"id" xorm:"not null pk autoincr comment('主键') INT(11)"`
	Name        string    `json:"name" xorm:"not null comment('学科名称') VARCHAR(100)"`

}
var systemsubject = "system_subject"


func(s *SystemSubject) GetRow() bool {
	has, err := mEngine.Get(s)
	if err==nil &&  has  {
		return true
	}
	return false
}
func  (s *SystemSubject) GetAll() ([]SystemSubject,error) {

	var systemsubjects []SystemSubject
	err:=mEngine.Find(&systemsubjects)
	return systemsubjects,err
}

func (s *SystemSubject) Add() error{
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}
	//var uid int64
	_,err:=session.Insert(s)
	if err!=nil {
		return err
	}

	return session.Commit()
}

func (s *SystemSubject) Update() error {
	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}
	if _, err := mEngine.Where("id = ?", s.Id).Update(s); err != nil {
		return err

	}
	return session.Commit()
}
func (s *SystemSubject) Delete() error {

	//TO: 将彻底删除所有相关的试题，知识点和题目来源！

	session := mEngine.NewSession()
	defer session.Close()
	// add Begin() before any action
	if err := session.Begin(); err != nil {
		// if returned then will rodefer session.Close()llback automatically
		return err
	}


	//删除学科信息
	if _, err := mEngine.Where("id = ?", s.Id).Delete(s); err != nil {
		return err

	}

	//delete from system_type where not exists (select 1 from system_subject_type where system_subject_type.type_id =system_type.id )
	//删除类型信息,如果这个类型不关联到任何学科
	if _, err :=mEngine.Exec("delete from "+systemtype+" where not exists (select 1 from "+systemsubjecttype+" where "+systemsubjecttype+".type_id ="+systemtype+".id )"); err != nil {
		return err

	}
	return session.Commit()

}

